package db;

import java.sql.SQLException;
import java.sql.Statement;

import parsing.ParsingTools;

public class DB_Tools {

	
	//################### Update DB ###################################
	public static int ConnectAndUpdateFile(String filePath){
		
		String query = ParsingTools.File2String(filePath);
		return ConnectAndUpdateString(query);
		
	}
	
	public static int ConnectAndUpdateString(String query){
		
		DB_Abstract myDB = new DB_SQL();
		if (myDB.connect() == 0){
			System.out.println("Failed To Connect");
			return 0;
		} else {
			System.out.println("Succed To Connect");
		}
		
		Statement stmt = String2Statements(query, myDB.getStmt());
				
		if (myDB.execStatment(stmt) == 0){
			System.out.println("Query Failed");
			return 0;
		} else {
			System.out.println("Query Succeeded");
		}
		
		
		myDB.closeConnection();
		
		return 1;
	}
	
	
	//################### Query DB ###################################
	
	public int ConnectAndQueryFile(String filePath){
		String query = ParsingTools.File2String(filePath);
		return ConnectAndQueryString(query);
	}
	
	public int ConnectAndQueryString(String query){
		
		DB_Abstract myDB = new DB_SQL();
		if (myDB.connect() == 0){
			System.out.println("Failed To Connect");
			return 0;
		} else {
			System.out.println("Succed To Connect");
		}
		
				
		if (myDB.execQuery(query) != null){
			System.out.println("Update Succeded");
		} else {
			System.out.println("Update Failed");
			return 0;
		}
		
		myDB.closeConnection();
		
		return 1;
	}

	
	//################### Tools ###################################
	
	public static Statement String2Statements(String query, Statement stmt){
		

		for (String Command: query.split(";")){
			try {
				if (Command.equalsIgnoreCase("\n"))
					continue;
				stmt.addBatch(Command + ";");
			} catch (SQLException e) {
				e.printStackTrace();
				return null;
			}
		}
		
		return stmt; 
	}

}
